using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;

namespace DeepMixWorkflow
{
    [DataContract]
    public class DeepMixTrack : INotifyPropertyChanged
    {
        [DataMember]
        public string Link { get; set; }

        [DataMember]
        public string Artist { get; set; }

        [DataMember]
        public string Title { get; set; }

        [DataMember]
        public TimeSpan StartTime { get; set; }

        [DataMember]
        public TimeSpan Duration { get; set; }

        private bool _isSelected;

        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                _isSelected = value;
                InvokePropertyChanged("IsSelected");
            }
        }

        public override int GetHashCode()
        {
            return Artist.GetHashCode()^Title.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return EqualsByArtistAndTitle((DeepMixTrack) obj);
        }

        public bool EqualsByArtistAndTitle(DeepMixTrack track)
        {
            if (track == null) return false;
            if (track.Artist != Artist) return false;
            if (track.Title != Title) return false;
            return true;
        }


        public event PropertyChangedEventHandler PropertyChanged;

        public void InvokePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }


        public override string ToString()
        {
            return string.Format(@"Artist:{0}, Song:{1}", Artist, Title);
        }

        public void Save(Stream stream)
        {
            var serializer = new DataContractSerializer(typeof (DeepMixTrack));

            serializer.WriteObject(stream, this);
        }

        public static DeepMixTrack Load(Stream stream)
        {
            var serializer = new DataContractSerializer(typeof (DeepMixTrack));
            return (DeepMixTrack) serializer.ReadObject(stream);
        }
        
        public DeepMixTrack Copy()
        {
            return new DeepMixTrack
                {
                    Artist = Artist,
                    Duration = Duration,
                    IsSelected = IsSelected,
                    Link = Link,
                    StartTime = StartTime,
                    Title = Title
                };
        }

        public static DeepMixTrack[] Copy(DeepMixTrack[] tracks)
        {
            return tracks.Select(t => t.Copy()).ToArray();
        }
    }

    [DataContract]
    public class DeepMixTrackContainer
    {
        [DataMember]
        public DeepMixTrack[] Tracks { get; set; }
    }
}